package com.elinkway.infinitemovies.ui.activity.play;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.PowerManager;

public class VideoPlayerScreenListener {
	
	private Context mContext;
	
	private ScreenBroadcastReceiver mScreenReceiver;
	
	private ScreenStateListener mScreenStateListener;
	
	public VideoPlayerScreenListener (Context context){
		mContext = context;
		mScreenReceiver = new ScreenBroadcastReceiver();
	}
	
	/**
	 * screen 状态广播接收者
	 * @author zhangshuo
	 */
	private class ScreenBroadcastReceiver extends BroadcastReceiver {

		private String action = null;

		@Override
		public void onReceive(Context context, Intent intent) {
			action = intent.getAction();
			// 开屏
			if (Intent.ACTION_SCREEN_ON.equals(action)) {
				mScreenStateListener.onScreenOn();
			} else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
				// 锁屏
				mScreenStateListener.onScreenOn();
			} else if (Intent.ACTION_USER_PRESENT.equals(action)) {
				// 解锁
				mScreenStateListener.onUserPresent();
			}
		}
	}
	
	public void begin(ScreenStateListener listener) {
		mScreenStateListener = listener;
		registerListener();
	}
	
	/**
	 * 获取screen状态
	 * zhangshuo
	 * 2014年5月8日 下午10:56:12
	 */
	private void getScreenState() {
		PowerManager manager = (PowerManager) mContext
				.getSystemService(Context.POWER_SERVICE);
		if (manager.isScreenOn()) {
			if (null != mScreenStateListener) {
				mScreenStateListener.onScreenOn();
			}
		} else {
			if (null != mScreenStateListener) {
				mScreenStateListener.onScreenOff();
			}
		}
	}
	
	
	public void unregisterListener() {
		mContext.unregisterReceiver(mScreenReceiver);
		mScreenReceiver = null;
		mContext = null;
	}
	
	private void registerListener() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_ON);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		filter.addAction(Intent.ACTION_USER_PRESENT);
		mContext.registerReceiver(mScreenReceiver, filter);
	}
	
	
	public interface ScreenStateListener {
		public void onScreenOn();
		
		public void onScreenOff();
		
		public void onUserPresent();
	}

}
